package com.alamiya.security.security;

import com.alamiya.security.entity.PublicUser;
import com.alamiya.security.service.IPublicUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Authenticate a user from the database.
 */
@Slf4j
@Component("userDetailsService")
public class UserModelDetailsService implements UserDetailsService {

    @Autowired
    private IPublicUserService userService;

    @Override
    public UserDetails loadUserByUsername(final String login) {
        log.debug("校验用户：'{}'", login);
        return userService
                .getOneWithRolesAndAuthorities(login)
                .map(publicUser -> createSpringSecurityUser(login, publicUser))
                .orElseThrow(() -> new UsernameNotFoundException("不存在用户：" + login));
    }

    private User createSpringSecurityUser(String lowercaseLogin, PublicUser publicUser) {
        if (!publicUser.isActivated()) {
            throw new UserNotActivatedException("用户： " + lowercaseLogin + " 未激活");
        }
        List<GrantedAuthority> grantedAuthorities = publicUser.getRoleNames().stream()
                .map(roleName -> new SimpleGrantedAuthority(roleName))
                .collect(Collectors.toList());
        return new User(publicUser.getUsername(),
                publicUser.getPassword(),
                grantedAuthorities);
    }
}
